package com.qing.transfomer.service.order.impl;

import com.alibaba.fastjson.JSONObject;
import com.qing.transfomer.client.QingFlowClient;
import com.qing.transfomer.dto.BaseRequestDTO;
import com.qing.transfomer.dto.mapping.CodeMappingResultDTO;
import com.qing.transfomer.dto.mapping.QingFlowResponseDTO;
import com.qing.transfomer.dto.order.GetOrderListRequestDTO;
import com.qing.transfomer.dto.qing.ApplyFilterRequestDTO;
import com.qing.transfomer.dto.qing.ApplyFilterResultDTO;
import com.qing.transfomer.service.AbstractBaseService;
import com.qing.transfomer.service.order.OderService;
import com.qing.transfomer.util.QingMappingUtil;
import com.qing.transfomer.vo.BaseResponseVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.util.List;

@Slf4j
@Service
public class OrderServiceImpl extends AbstractBaseService implements OderService {

    @Resource
    private QingFlowClient qingFlowClient;

    @Override
    public BaseResponseVO<Integer> getOrderListBubble(BaseRequestDTO baseRequestDTO) {
        BaseResponseVO<Integer> responseVO = new BaseResponseVO<>();
        URI uri = getApplyFilterURI(baseRequestDTO);
        ApplyFilterRequestDTO requestDTO = new ApplyFilterRequestDTO();
        requestDTO.setPageNum(1);
        requestDTO.setPageSize(1);
        requestDTO.setQueryKey("待接单");
        log.info("uri: {}, requestDTO: {}", uri, requestDTO);
        QingFlowResponseDTO<ApplyFilterResultDTO> qingFlowResponseDTO = qingFlowClient.applyFilter(uri, baseRequestDTO.getAccessToken(), requestDTO);
        log.info("qingFlowResponseDTO: {}", qingFlowResponseDTO);

        if (qingFlowResponseDTO.getErrCode() == QingFlowResponseDTO.SUCCESS_CODE) {
            ApplyFilterResultDTO result = qingFlowResponseDTO.getResult();
            responseVO.setData(result.getResultAmount());
        }

        return responseVO;
    }

    @Override
    public BaseResponseVO<List<JSONObject>> getOrderList(GetOrderListRequestDTO getOrderListRequestDTO) {
        BaseResponseVO<List<JSONObject>> responseVO = new BaseResponseVO<>();
        CodeMappingResultDTO codeMappingResult = getCodeMappingResult(getOrderListRequestDTO);
        URI uri = getApplyFilterURI(getOrderListRequestDTO, codeMappingResult);
        ApplyFilterRequestDTO applyFilterRequestDTO = QingMappingUtil.transferToApplyFilterRequest(getOrderListRequestDTO, codeMappingResult);
        log.info("uri: {}, requestDTO: {}", uri, applyFilterRequestDTO);
        QingFlowResponseDTO<ApplyFilterResultDTO> qingFlowResponseDTO = qingFlowClient.applyFilter(uri, getOrderListRequestDTO.getAccessToken(), applyFilterRequestDTO);
        List<JSONObject> jsonObjects = QingMappingUtil.transferApplyFilterResponse(qingFlowResponseDTO, codeMappingResult);
        responseVO.setData(jsonObjects);

        return responseVO;
    }
}
